SELECT OBJECT_NAME( B.OBJECT_ID ) AS TableName, b.name AS Index_Name, CASE 
                                                                           WHEN ps.avg_fragmentation_in_percent
                                                                                > 30 THEN 
                                                                                'REBUILD 
          WITH (
              PAD_INDEX =OFF, STATISTICS_NORECOMPUTE= OFF, ALLOW_ROW_LOCKS =OFF, 
              ALLOW_PAGE_LOCKS= OFF, ONLINE =ON, SORT_IN_TEMPDB =ON, MAXDOP = 2
          )'
                                                                           ELSE 'REORGANIZE'
                                                                      END AS INDEX_OPTION, 
       avg_fragmentation_in_percent AS Fragmentation_Size, ps.Page_count AS TotalPage
FROM   sys.dm_db_index_physical_stats ( DB_ID(), NULL, NULL, NULL, NULL ) AS ps
       INNER JOIN sys.indexes AS b
            ON  ps.OBJECT_ID = b.OBJECT_ID AND
                ps.index_id = b.index_id
WHERE  ps.database_id = DB_ID() AND
       b.name IS NOT NULL AND
       ps.avg_fragmentation_in_percent > 10
ORDER BY
       Fragmentation_Size DESC

SELECT ' ALTER INDEX '+ b.name + ' ON '+ OBJECT_NAME( B.OBJECT_ID ) +' '+ CASE 
                                                                           WHEN ps.avg_fragmentation_in_percent
                                                                                > 30 THEN 
                                                                                'REBUILD 
          WITH ( PAD_INDEX =OFF, STATISTICS_NORECOMPUTE= OFF, ALLOW_ROW_LOCKS =OFF, 
              ALLOW_PAGE_LOCKS= OFF, ONLINE =ON, SORT_IN_TEMPDB =ON, MAXDOP = 2 )'
                                                                           ELSE 'REORGANIZE'
                                                                      END AS INDEX_OPTION, 
       avg_fragmentation_in_percent AS Fragmentation_Size, ps.Page_count AS TotalPage
FROM   sys.dm_db_index_physical_stats ( DB_ID(), NULL, NULL, NULL, NULL ) AS ps
       INNER JOIN sys.indexes AS b
            ON  ps.OBJECT_ID = b.OBJECT_ID AND
                ps.index_id = b.index_id
WHERE  ps.database_id = DB_ID() AND
       b.name IS NOT NULL AND
       ps.avg_fragmentation_in_percent > 10
ORDER BY
       Fragmentation_Size DESC       
       